package com.qs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qs.constant.CacheConstant;
import com.qs.es.service.EsGoodsService;
import com.qs.exception.ServiceException;
import com.qs.mapper.CollectGoodsMapper;
import com.qs.mapper.CommentMapper;
import com.qs.mapper.GoodsMapper;
import com.qs.mapper.StoreMapper;
import com.qs.model.dto.GoodsDetailDto;
import com.qs.model.dto.GoodsIndexDto;
import com.qs.model.entity.CollectGoods;
import com.qs.model.entity.Comment;
import com.qs.model.entity.Goods;
import com.qs.model.entity.Store;
import com.qs.response.ResponseEnum;
import com.qs.service.IAsyncService;
import com.qs.service.IGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-03-23
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    private final CollectGoodsMapper collectGoodsMapper;

    private final EsGoodsService esGoodsService;

    private final CommentMapper commentMapper;

    private final RedisTemplate redisTemplate;

    private final StoreMapper storeMapper;

    private final IAsyncService asyncService;

    @Override
    public Map<String,Object> findIndexImage() {
        //先去redis查询
        Map<String,Object> result = (Map<String,Object>) redisTemplate.opsForValue().get(CacheConstant.INDEX_GOODS_IMAGE);
        if(!CollectionUtils.isEmpty(result)){
            log.info("获取首页商品轮播图走缓存.......");
            return result;
        }
        List<String> images = baseMapper.findIndexImage();
        List<Integer> goodsId = baseMapper.findIndexGoodsId();

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("images",images);
        map.put("ids",goodsId);
        //放入redis缓存
        if(!CollectionUtils.isEmpty(images)){
            log.info("获取首页商品轮播图走数据库.......");
            redisTemplate.opsForValue().set(CacheConstant.INDEX_GOODS_IMAGE,map,CacheConstant.INDEX_GOODS_IMAGE_EXPIRE,TimeUnit.MINUTES);
            return map;
        }
        return null;
    }

    @Override
    public List<GoodsIndexDto> findIndexHotGoods() {
        List<GoodsIndexDto> result = (List<GoodsIndexDto>) redisTemplate.opsForValue().get(CacheConstant.INDEX_GOODS_HOT);
        if(!CollectionUtils.isEmpty(result)){
            log.info("获取首页热卖商品走缓存.......");
            return result;
        }
        List<Goods> goodsList = baseMapper.findIndexHotGoods();
        if(!CollectionUtils.isEmpty(goodsList)){
            List<GoodsIndexDto> resultList = goodsList.stream().map(goods -> {
                //获取每个商品的收藏量
                Long collectNum = collectGoodsMapper.selectCount(new QueryWrapper<CollectGoods>()
                        .eq("goods_id", goods.getId()));
                //获取每个商品的评论量
                Long commentNum = commentMapper.selectCount(new QueryWrapper<Comment>()
                        .eq("goods_id", goods.getId()));

                GoodsIndexDto dto = new GoodsIndexDto();
                dto.setId(goods.getId());
                dto.setGoodsName(goods.getName());
                dto.setImage(goods.getImage());
                dto.setPrice(goods.getPrice());
                dto.setBrowse(goods.getBrowse());
                dto.setSale(goods.getSale());
                dto.setCollectNum(collectNum);
                dto.setCommentNum(commentNum);
                return dto;
            }).collect(Collectors.toList());
            log.info("获取首页热卖商品走数据库.......");
            //放入redis缓存
            redisTemplate.opsForValue().set(CacheConstant.INDEX_GOODS_HOT,resultList,CacheConstant.INDEX_GOODS_HOT_EXPIRE,TimeUnit.MINUTES);
            return resultList;
        }
        return null;
    }

    @Override
    public List findRecommendGoods() {
        List<Goods> goodsList = baseMapper.findRecommendGoods();
        if(!CollectionUtils.isEmpty(goodsList)) {
            List<GoodsIndexDto> dtoList = new ArrayList<GoodsIndexDto>();
            goodsList.stream().forEach(goods -> {
                //获取每个商品的收藏量
                Long collectNum = collectGoodsMapper.selectCount(new QueryWrapper<CollectGoods>()
                        .eq("goods_id", goods.getId()));
                //获取每个商品的评论量
                Long commentNum = commentMapper.selectCount(new QueryWrapper<Comment>()
                        .eq("goods_id", goods.getId()));

                GoodsIndexDto dto = new GoodsIndexDto();
                dto.setId(goods.getId());
                dto.setGoodsName(goods.getName());
                dto.setImage(goods.getImage());
                dto.setPrice(goods.getPrice());
                dto.setBrowse(goods.getBrowse());
                dto.setSale(goods.getSale());
                dto.setCollectNum(collectNum);
                dto.setCommentNum(commentNum);
                dtoList.add(dto);
            });
            //封装数据
            // 每组数据量
            int groupSize = 6;
            int groupCount = (dtoList.size() + groupSize - 1) / groupSize;
            List result = new ArrayList();
            for (int i = 0; i < groupCount; i++) {
                int startIndex = i * groupSize;
                int endIndex = Math.min(startIndex + groupSize, dtoList.size());
                List<GoodsIndexDto> group = dtoList.subList(startIndex, endIndex);
                result.add(group);
            }
            return result;
        }
        return null;
    }

    @Override
    public List<GoodsIndexDto> searchFrontList(List<Integer> ids, String name) {
        List<GoodsIndexDto> list = null;
        try {
            list = esGoodsService.searchGoodsFrontList(ids,name);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    @Override
    public List<Integer> frontSearchList(String param) {
        if(StringUtils.isBlank(param)){
            throw new ServiceException(ResponseEnum.BAD_REQUEST);
        }
        List<Integer> goodsIds = null;
        try {
            goodsIds = esGoodsService.frontSearchList(param);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return goodsIds;
    }

    @Override
    public GoodsDetailDto findGoodsDetail(Integer id) {
        if(null == id) {
            throw new ServiceException(ResponseEnum.BAD_REQUEST);
        }
        Goods goods = baseMapper.selectById(id);
        if(null == goods) {
            throw new ServiceException(ResponseEnum.GOODS_NOT_FOUND);
        }
        //根据商品id获取店铺名称
        Store store = storeMapper.selectById(goods.getStoreId());

        GoodsDetailDto goodsDetailDto = new GoodsDetailDto();
        goodsDetailDto.setDetail(goods.getDetail());
        goodsDetailDto.setId(goods.getId());
        goodsDetailDto.setStoreId(store.getId());
        goodsDetailDto.setGoodsName(goods.getName());
        goodsDetailDto.setStoreName(store.getHomeName());
        goodsDetailDto.setPrice(goods.getPrice());
        goodsDetailDto.setImage(goods.getImage());
        goodsDetailDto.setSale(goods.getSale());

        //异步将商品浏览量加1
        asyncService.incrementViewCount(id);
        return goodsDetailDto;
    }
}
